//
//  PeopleNearbyViewController.m
//  Custom_Weibo
//
//  Created by LEO on 12/18/15.
//  Copyright © 2015 Leo_Lei. All rights reserved.
//

#import "PeopleNearbyViewController.h"
#import "WeiboAnnotationView.h"
#import "WeiboAnnotation.h"
#import "DetailViewController.h"

@interface PeopleNearbyViewController () {
    CLLocationManager *_locationManager;
    MKMapView *_mapView;
}

@end

@implementation PeopleNearbyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"People Nearby";
    
    [self showOntheMap];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - SHOW_LOCATION
- (void)showOntheMap {
    _mapView = [[MKMapView alloc] initWithFrame:self.view.bounds];
    
    //  Show user location on the map.
    _mapView.showsUserLocation = YES;
    
    //  Set map type for show.
    _mapView.mapType = MKMapTypeStandard;
    
    /*  Set user tracking mode.(Since you want to custom the showing scope by yourself, you will rewrite the delegate method of 'didUpdateLocation').
     */
    _mapView.userTrackingMode = MKUserTrackingModeFollowWithHeading;
    
    _mapView.delegate = self;
    [self.view addSubview:_mapView];
}

#pragma mark GET_WEIBO_NEARBY
- (void)peopleNearbyWithLongitude:(NSString *)longitude latitude:(NSString *)latitude {
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:longitude forKey:@"long"];
    [params setObject:latitude forKey:@"lat"];
    [params setObject:@50 forKey:@"count"];
    
    [NetworkService requestAFUrl:kNearby_Timeline
                      httpMethod:@"GET"
                          params:params
                            data:nil
                           block:^(id result, NSURLResponse *response, NSError *error) {
        NSArray *statuses = [result objectForKey:@"statuses"];
        NSMutableArray *annotationArray = [[NSMutableArray alloc] init];
        
        for (NSDictionary *dic in statuses) {
            WeiboModel *weiboModel = [[WeiboModel alloc] initWithDataDic:dic];
            
            //  If user doesn't get the nearby weibo information, the abandon it.
            if (![weiboModel.geo isEqual:[NSNull null]]) {
                WeiboAnnotation *annotation = [[WeiboAnnotation alloc] init];
                annotation.weiboModel = weiboModel;
                [annotationArray addObject:annotation];
            }
        }
        [_mapView addAnnotations:annotationArray];
    }];
}

#pragma mark - MAPVIEW_DELEGATE
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
    //  1)Get the longitude and the latitude of the position.
    CLLocation *location = userLocation.location;
    CLLocationCoordinate2D coordinate = location.coordinate;
    
    //  2)Get nearby weibo through network.
    NSString *longitude = [NSString stringWithFormat:@"%lf", coordinate.longitude];
    NSString *latitude = [NSString stringWithFormat:@"%lf", coordinate.latitude];
    [self peopleNearbyWithLongitude:longitude latitude:latitude];
    
    /*  3)Set the scope for showing area.The smaler the number is, the more 
     accurate for location.
     */
    MKCoordinateSpan span = {0.1, 0.1};
    
    //  Show the center of showing area.
    CLLocationCoordinate2D center = coordinate;
    MKCoordinateRegion region = {center, span};
    
    [mapView setRegion:region];
}

#pragma mark ANIMATED_WHEN_SHOW_ANNOTATIONS
- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray<MKAnnotationView *> *)views {
    for (NSInteger i = 0; i < views.count; i++) {
        WeiboAnnotationView *view = (WeiboAnnotationView *)views[i];
        
        //  If the annotation is the system annotation, we don't set animations.
        if (![view isKindOfClass:[WeiboAnnotationView class]]) {
            continue;
        }
        
        //  If the annotation is customerized, we set default status as follows.
        view.transform = CGAffineTransformMakeScale(0.5, 0.5);
        view.alpha = 0;
        
        [UIView animateWithDuration:1 animations:^{
            //  When each nearby weibo is showed, we set delay for each one.
            [UIView setAnimationDelay:i * 0.1];
            view.transform = CGAffineTransformMakeScale(1.5, 1.5);
            view.alpha = 1;
        } completion:^(BOOL finished) {
            //  When all the nearby weibo are showed, we reset it as normal size.
            if (finished) {
                [UIView animateWithDuration:0.3 animations:^{
                    view.transform = CGAffineTransformMakeScale(1, 1);
                }];
            }
        }];
    }
}

#pragma mark TURNS_INTO_WEIBO_DETAIL
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view {
    DetailViewController *detailVC = [[DetailViewController alloc] init];
    
    //  Get the model, if it is selected.
    WeiboAnnotation *annotation = view.annotation;
    
    WeiboModel *weiboModel = annotation.weiboModel;
    WeiboViewLayoutFrame *layoutFrame = [[WeiboViewLayoutFrame alloc] init];
    layoutFrame.weiboModel = weiboModel;
    detailVC.layoutFrame = layoutFrame;
    
    [self.navigationController pushViewController:detailVC animated:YES];
}

#pragma mark - CUSTOM_ANNOTATION_VIEW
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
    /*  When we add different types of annotation, we should distinguish them
     from each other
     */
    if ([annotation isKindOfClass:[MKUserLocation class]]) {
        //  If we return nil there, then the annotation is the system annotation.
        return nil;
    }
    
    if ([annotation isKindOfClass:[WeiboAnnotation class]]) {
        WeiboAnnotationView *annotaionView = (WeiboAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:kAnnotationCellID];
        if (annotaionView == nil) {
            annotaionView = [[WeiboAnnotationView alloc] initWithAnnotation:annotation
                                                            reuseIdentifier:kAnnotationCellID];
        }
        annotaionView.annotation = annotation;
        return annotaionView;
    }
    return nil;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
